import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:xcite/core/services/open_launcher.dart';
import 'package:xcite/core/widgets/loading_widget.dart';

import '../../core/models/user_model.dart';
import '../../core/providers/user_provider.dart';
import '../../core/utils/toast_helper.dart';
import '../../core/utils/popup_helper.dart';

class UserSettingsScreen extends ConsumerStatefulWidget {
  const UserSettingsScreen({super.key});

  @override
  ConsumerState<UserSettingsScreen> createState() => _UserSettingsScreenState();
}

class _UserSettingsScreenState extends ConsumerState<UserSettingsScreen> {
  @override
  Widget build(BuildContext context) {
    final currentUser = ref.watch(currentUserProvider);

    if (currentUser == null) {
      return Scaffold(
        body: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0xFF2AB061), Color(0xFF1E8B4F)],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            ),
          ),
          child: SafeArea(
            child:
                [
                  Text(
                    'Please login first',
                    style: TextStyle(
                      fontSize: 18.sp,
                      color: Colors.white,
                      fontWeight: FontWeight.w600,
                    ),
                  ).center(),
                ].toColumn(),
          ),
        ),
      );
    }

    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/common_bg_2.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child:
              [
                _buildHeaderSection(),

                SizedBox(height: 20.h),

                _buildUserInfoSection(currentUser),

                SizedBox(height: 40.h),

                _buildSettingsOptions(),

                Spacer(),

                _buildLogoutButton(),

                SizedBox(height: 40.h),
              ].toColumn(),
        ),
      ),
    );
  }

  Widget _buildHeaderSection() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
      child:
          [
            Container(
              width: 30.w,
              height: 30.w,
              decoration: BoxDecoration(
                color: Colors.black,
                shape: BoxShape.circle,
              ),
              child:
                  Icon(
                    Icons.arrow_back_ios,
                  ).iconSize(18.sp).iconColor(Colors.white).center(),
            ).inkWell(onTap: () => GoRouter.of(context).pop()),

            Spacer(),

            Text(
              'Set Up',
              style: TextStyle(
                fontSize: 24.sp,
                color: Colors.black,
                fontWeight: FontWeight.bold,
                fontFamily: 'PoetsenOne',
              ),
            ),

            Spacer(),

            SizedBox(width: 40.w),
          ].toRow(),
    );
  }

  Widget _buildUserInfoSection(UserDataEntity currentUser) {
    return [
      Container(
        width: 100.w,
        height: 100.w,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          border: Border.all(color: Colors.black, width: 3.w),
          image: DecorationImage(
            image: AssetImage(currentUser.avatar),
            fit: BoxFit.cover,
          ),
        ),
      ),

      SizedBox(height: 16.h),

      Text(
        currentUser.username,
        style: TextStyle(
          fontSize: 24.sp,
          color: Colors.white,
          fontWeight: FontWeight.bold,
        ),
      ),

      SizedBox(height: 8.h),

      Text(
        'Last Login: ${_formatLastLoginTime(currentUser.lastLoginTime)}',
        style: TextStyle(
          fontSize: 14.sp,
          color: Colors.white.withValues(alpha: 0.8),
        ),
      ),
    ].toColumn().center();
  }

  Widget _buildSettingsOptions() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child:
          [
            _buildSettingItem(
              'Privacy Policy',
              onTap: () => _openPrivacyPolicy(),
            ),
            SizedBox(height: 16.h),
            _buildSettingItem(
              'Terms Of Service',
              onTap: () => _openTermsOfService(),
            ),
            SizedBox(height: 16.h),
            _buildSettingItem(
              'Delete Account',
              onTap: () => _showDeleteAccountDialog(),
            ),
          ].toColumn(),
    );
  }

  Widget _buildSettingItem(String title, {required VoidCallback onTap}) {
    return Container(
      padding: EdgeInsets.only(right: 2.w, bottom: 2.w),
      decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.circular(10.r),
      ),
      child: Container(
        height: 56.h,
        padding: EdgeInsets.symmetric(horizontal: 20.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(10.r),
          border: Border.all(color: Colors.black, width: 2.w),
        ),
        child:
            [
              Text(
                title,
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Colors.black,
                  fontWeight: FontWeight.w500,
                ),
              ),
              Spacer(),
              Icon(
                Icons.arrow_forward_ios,
              ).iconSize(16.sp).iconColor(Colors.black),
            ].toRow(),
      ).inkWell(onTap: onTap),
    );
  }

  Widget _buildLogoutButton() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 20.w),
      child: Image.asset(
        'assets/resources/logout_button.png',
        width: double.infinity,
        height: 56.h,
        fit: BoxFit.fill,
      ).inkWell(onTap: _handleLogout),
    );
  }

  String _formatLastLoginTime(DateTime lastLoginTime) {
    final now = DateTime.now();
    final difference = now.difference(lastLoginTime);

    if (difference.inDays > 0) {
      return '${lastLoginTime.month}/${lastLoginTime.day}/${lastLoginTime.year}';
    } else if (difference.inHours > 0) {
      return '${difference.inHours} hours ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes} minutes ago';
    } else {
      return 'Just now';
    }
  }

  void _openPrivacyPolicy() async {
    Open.openLaunch(
      'https://www.freeprivacypolicy.com/live/9c658f5d-4d8a-440f-9dca-6da06109b53d',
    );
  }

  void _openTermsOfService() async {
    Open.openLaunch(
      'https://www.freeprivacypolicy.com/live/7ce39277-9d4b-46e1-a768-096bf2f6d765',
    );
  }

  void _showDeleteAccountDialog() {
    PopupHelper.showDeleteAccountDialog(
      context,
      onDeletePressed: _handleDeleteAccount,
      onCancelPressed: () {},
    );
  }

  void _handleDeleteAccount() async {
    try {
      LoadingWidget.showFullScreen(context);
      final userNotifier = ref.read(userProvider.notifier);
      await userNotifier.logout();

      if (mounted) {
        await Future.delayed(Duration(milliseconds: 1500));
        LoadingWidget.hide(context);
        ToastHelper.success('Account deleted successfully', context: context);

        if (mounted) {
          GoRouter.of(context).go('/');
        }
      }
    } catch (e) {
      if (mounted) {
        ToastHelper.error('Failed to delete account', context: context);
      }
    }
  }

  void _handleLogout() async {
    try {
      LoadingWidget.showFullScreen(context);
      final userNotifier = ref.read(userProvider.notifier);
      await userNotifier.logout();

      if (mounted) {
        await Future.delayed(Duration(milliseconds: 1500));
        LoadingWidget.hide(context);
        ToastHelper.success('Logged out successfully', context: context);

        if (mounted) {
          GoRouter.of(context).go('/');
        }
      }
    } catch (e) {
      if (mounted) {
        ToastHelper.error('Failed to logout', context: context);
      }
    }
  }
}
